package com.hliu.shiro.realm;

import com.hliu.shiro.model.Permission;
import com.hliu.shiro.model.Role;
import com.hliu.shiro.model.User;
import com.hliu.shiro.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authc.credential.PasswordService;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * author: 6
 * date: 13-4-17
 */
public class NormalRealm extends AuthorizingRealm {
	@Autowired
	private IUserService iUserService;

	//授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		if (iUserService.getExistUserByUserName(principals.toString())) {
			User user = iUserService.getUserAllRolsAndPermission(principals.toString());
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			for (Role role : user.getRoles()) {
				info.addRole(role.getRoleName());
				for (Permission permission : role.getPermissions()) {
					info.addStringPermission(permission.getPermissionName());
				}
			}
			return info;
		}
		return null;
	}

	//认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
		Object principal = usernamePasswordToken.getPrincipal();
		Object credentials = usernamePasswordToken.getCredentials();
		User user = iUserService.getUserByUserName(principal.toString());
		if (user != null) {
			PasswordService ps = new DefaultPasswordService();
			if (ps.passwordsMatch(credentials,user.getPassword())) {
				SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials, getName());
				return info;
			}
			throw  new IncorrectCredentialsException("密码错误");
		}
		throw  new UnknownAccountException("用户名错误");
	}
}
